package xyz.flowlight.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.flowlight.domain.entity.Cart;
import xyz.flowlight.domain.entity.LikeRecord;
import xyz.flowlight.domain.entity.Product;
import xyz.flowlight.domain.response.ResponseResult;
import xyz.flowlight.mapper.CartMapper;
import xyz.flowlight.mapper.LikeMapper;
import xyz.flowlight.mapper.ProductMapper;
import xyz.flowlight.service.ProductService;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service("productService")
@Transactional
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Autowired
    ProductMapper productMapper;

    @Autowired
    CartMapper cartMapper;

    @Override
    public ResponseResult<List<Product>> searchProducts(String keyword) {
        List<Product> products = productMapper.findByNameContaining(keyword);
        return ResponseResult.success(products);
    }

    @Override
    public ResponseResult<Void> addToCart(Integer userId, Integer productId, Integer quantity) {
        Product product = productMapper.selectById(productId);
        Cart cartItem = cartMapper.findByUserAndProduct(userId, productId);
        if (cartItem != null) {
            cartItem.setQuantity(cartItem.getQuantity() + quantity);
        } else {
            cartItem = new Cart();
            cartItem.setUserId(userId);
            cartItem.setProductId(productId);
            cartItem.setQuantity(quantity);
            cartMapper.insert(cartItem);
            return ResponseResult.success();
        }
        return ResponseResult.success();

    }

    public void decreaseStock(Integer productId) {
        Product product = productMapper.selectById(productId) ;
        if (product.getStock() <= 0) {
            throw new RuntimeException("库存不足");
        }
        product.setStock(product.getStock() - 1);
        productMapper.updateById(product);
    }

    @Override
    public List<Product> getAllProducts() {
        return productMapper.selectList(null);
    }
}


